from django.http import HttpResponse
from product.models import Product
from django.core.paginator import Paginator

def limit_query_view(request):
    # 限制数据返回
    # 1. 切片操作 价格最高的前三条数据
    products = Product.objects.all().order_by('-price')[:3]
    
    # 2.从第二条取到第五条
    products = Product.objects.all()[1:5]
    print(products)

    # 3.分页
    prodoucts = Product.objects.all().order_by('price')
    paginator = Paginator(prodoucts, 2)
    
    # 获取当前页码,page(1)表示获取第一页
    page_products = paginator.page(2)
    
    # 获取当前的总页数
    total_page = paginator.num_pages
    print(total_page)
    # 获取当前页的数据
    for product in page_products:
        print(product)

    # 检查上一页
    if page_products.has_previous():
        previous = page_products.previous_page_number()
        print(f"当前页码:{page_products}, 上一页：第{previous}页")
    else:
        print("没有上一页了")

    # 检查下一页
    if page_products.has_next():
        next_page = page_products.next_page_number()
        print(f"当前页码:{page_products}, 下一页：第{next_page}页")
    else:
        print("没有下一页了")
    return HttpResponse(f"{products}")